package com.elong.android.specialhouse.ui;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;

/**
 * Created by kaiqi.li on 2015/8/7.
 *
 * @descripsion
 */
public class LimitedListView extends LinearLayout{

    private final DataSetObserver mDataSetObserver ;
    private ListAdapter mAdapter ;
    private AdapterView.OnItemClickListener mOnItemClickListener ;

    public LimitedListView(Context context, AttributeSet attrs){
        super(context,attrs);
        this.mDataSetObserver = new DataSetObserver() {
            @Override
            public void onChanged() {
                syncDataFromAdapter();
                super.onChanged();
            }

            @Override
            public void onInvalidated() {
                syncDataFromAdapter();
                super.onInvalidated();
            }
        } ;
    }

    public void setAdapter(ListAdapter adapter) {
        ensureDataSetObserverUnregistered();
        this.mAdapter = adapter ;
        if (this.mAdapter != null) {
            this.mAdapter.registerDataSetObserver(mDataSetObserver);
        }
        syncDataFromAdapter();
    }

    public Object getItemAtPosition(int position) {
        return mAdapter == null ? null : mAdapter.getItem(position);
    }

    public void setSelection(int i){
        getChildAt(i).setSelected(true);
    }

    public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
        this.mOnItemClickListener = listener ;
    }

    public ListAdapter getAdapter() {
        return mAdapter ;
    }

    public int getCount() {
        return mAdapter == null ? 0 :mAdapter.getCount() ;
    }

    protected void ensureDataSetObserverUnregistered() {
        if (this.mAdapter != null) {
            this.mAdapter.unregisterDataSetObserver(mDataSetObserver);
        }
    }

    private void syncDataFromAdapter(){
        removeAllViews();
        if (mAdapter != null) {
            int count = mAdapter.getCount() ;
            for (int i = 0; i < count; i++) {
                View view = mAdapter.getView(i,null,this);
                boolean enabled = mAdapter.isEnabled(i);
                if (enabled) {
                    final int position = i ;
                    final long id = mAdapter.getItemId(position);
                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (mOnItemClickListener != null) {
                                mOnItemClickListener.onItemClick(null,v,position,id);
                            }
                        }
                    });
                }
                addView(view);

            }
        }
    }

}
